<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus, CaretRight } from '@element-plus/icons-vue'
import type { TSystemPage } from '../../Types/system'
import { standardDateTime } from '../../Tools/Time/date'
import {
	getSystemPages,
	addSystemPage,
	updateSystemPage,
	deleteSystemPage,
	updatePageEnabled,
	updatePageAllowUser
} from '../../api/system/page'

// 默认表单
const defaultForm: TSystemPage = {
	name: '',
	path: '',
	component: '',
	icon: '',
	isEnabled: 1,
	allowUser: '[1,2,3,4,5]',
	createTime: '',
	updateTime: ''
}

// 状态定义
const loading = ref(false)
const pageList = ref<TSystemPage[]>([])
const formRef = ref<FormInstance>()
// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const loadingDialog = ref(false)
const currentPage = ref<TSystemPage>({ ...defaultForm })

// 页面分组相关
const groupedPages = computed(() => {
	const groups: Record<string, TSystemPage[]> = {
		teacher: [],
		counsellor: [],
		my: [],
		backend: [],
		other: []
	}

	pageList.value.forEach((page) => {
		// 去掉开头的斜杠并分割路径
		const pathParts = page.path.replace(/^\//, '').split('/')

		// 如果路径至少有一级
		if (pathParts.length > 0 && pathParts[0]) {
			const rootPath = pathParts[0].toLowerCase()

			// 检查是否是指定的四个分组之一
			if (groups[rootPath] !== undefined) {
				groups[rootPath].push(page)
			} else {
				// 不是指定组的放入"other"
				groups.other.push(page)
			}
		} else {
			// 空路径也放入"other"
			groups.other.push(page)
		}
	})

	// 删除空组
	Object.keys(groups).forEach((key) => {
		if (groups[key].length === 0) {
			delete groups[key]
		}
	})

	return groups
})

// 组名映射
const groupNameMap: Record<string, string> = {
	teacher: '任课老师',
	counsellor: '辅导员',
	my: '个人中心',
	backend: '后台管理',
	other: '其它'
}

// 获取组显示名称
const getGroupDisplayName = (key: string) => {
	return groupNameMap[key] || key
}

// 展开状态管理
const expandedGroups = ref<Record<string, boolean>>({})

// 切换组的展开/折叠状态
const toggleGroup = (groupName: string) => {
	expandedGroups.value[groupName] = !expandedGroups.value[groupName]
}

// 初始化所有组为折叠状态
const initExpandedGroups = () => {
	const groups = Object.keys(groupedPages.value)
	groups.forEach((group) => {
		expandedGroups.value[group] = false
	})
}

// 方法定义
// 获取页面列表
const getPageList = async () => {
	loading.value = true
	try {
		const res = await getSystemPages()
		pageList.value = res.data.data
		// 初始化展开状态
		initExpandedGroups()
	} catch {
		ElMessage.error('获取页面列表失败')
	} finally {
		loading.value = false
	}
}

// 处理页面状态更改
const handleStatusChange = async (row: TSystemPage) => {
	try {
		if (row.id) {
			await updatePageEnabled({ id: row.id, isEnabled: row.isEnabled as unknown as number })
			ElMessage.success('状态更新成功')
		}
	} catch {
		row.isEnabled = row.isEnabled ? 0 : 1
		ElMessage.error('状态更新失败')
	}
}

// 处理允许用户更改
const handleAllowUserChange = async (row: TSystemPage, userTypes: number[]) => {
	try {
		if (row.id) {
			const allowUser = JSON.stringify(userTypes)
			row.allowUser = allowUser
			await updatePageAllowUser({ id: row.id, allowUser })
			ElMessage.success('权限更新成功')
		}
	} catch {
		ElMessage.error('权限更新失败')
		getPageList() // 重新加载以恢复正确的数据
	}
}

// 处理删除页面
const handleDelete = (row: TSystemPage) => {
	ElMessageBox.confirm('确定要删除该页面吗？', '提示', {
		type: 'warning'
	}).then(async () => {
		try {
			if (row.id) {
				await deleteSystemPage(row.id)
				ElMessage.success('删除成功')
				getPageList()
			}
		} catch {
			ElMessage.error('删除失败')
		}
	})
}

// 打开弹窗
const openDialog = (type: 'add' | 'edit', row?: TSystemPage) => {
	dialogTitle.value = type === 'add' ? '添加页面' : '编辑页面'
	currentPage.value = row ? { ...row } : { ...defaultForm }
	initSelectedUserTypes()
	dialogVisible.value = true
	loadingDialog.value = false
}

// 提交表单
const pageSubmit = async (page: TSystemPage) => {
	if (!formRef.value) return
	// 等待表单验证
	await formRef.value.validate(async (valid) => {
		if (!valid) return

		try {
			if (page.id) {
				await updateSystemPage(page)
				ElMessage.success('编辑成功')
			} else {
				await addSystemPage(page)
				ElMessage.success('添加成功')
			}
			dialogVisible.value = false
			getPageList()
		} catch {
			ElMessage.error(page.id ? '编辑失败' : '添加失败')
		}
	})
}

// 重置表单
const resetForm = () => {
	currentPage.value = { ...defaultForm }
	initSelectedUserTypes()
	formRef.value?.resetFields()
}

// 表单验证规则
const formRule = {
	name: [{ required: true, message: '请输入页面名称', trigger: 'blur' }],
	path: [{ required: true, message: '请输入页面路径', trigger: 'blur' }],
	component: [{ required: true, message: '请输入所在路径', trigger: 'blur' }]
}

// 生命周期
onMounted(getPageList)

// 用户类型映射
const userTypeMap = {
	1: '学生',
	2: '老师',
	3: '辅导员',
	4: '管理员',
	5: '开发者'
}

// 格式化允许用户显示
const formatAllowUser = (allowUser: string | undefined) => {
	if (!allowUser) return '无权限'

	try {
		const userTypes = JSON.parse(allowUser)
		return userTypes
			.map((type: number) => userTypeMap[type as keyof typeof userTypeMap] || `未知(${type})`)
			.join('、')
	} catch (e) {
		return '格式错误'
	}
}

// 用户选择数据
const userOptions = [
	{ label: '学生', value: 1 },
	{ label: '老师', value: 2 },
	{ label: '辅导员', value: 3 },
	{ label: '管理员', value: 4 },
	{ label: '开发者', value: 5 }
]

// 当前选择的用户类型
const selectedUserTypes = ref<number[]>([])

// 处理用户类型变化
const handleUserTypesChange = (types: number[]) => {
	currentPage.value.allowUser = JSON.stringify(types)
}

// 初始化选择的用户类型
const initSelectedUserTypes = () => {
	if (currentPage.value.allowUser) {
		try {
			selectedUserTypes.value = JSON.parse(currentPage.value.allowUser)
		} catch {
			selectedUserTypes.value = [1, 2, 3, 4, 5] // 默认全选
			currentPage.value.allowUser = '[1,2,3,4,5]'
		}
	} else {
		selectedUserTypes.value = [1, 2, 3, 4, 5] // 默认全选
		currentPage.value.allowUser = '[1,2,3,4,5]'
	}
}

// 用户权限编辑弹窗
const userEditDialogVisible = ref(false)
const editingPage = ref<TSystemPage | null>(null)
const editingUserTypes = ref<number[]>([])

// 打开用户权限编辑弹窗
const openUserEditDialog = (row: TSystemPage) => {
	editingPage.value = { ...row }
	try {
		editingUserTypes.value = row.allowUser ? JSON.parse(row.allowUser) : []
	} catch {
		editingUserTypes.value = []
	}
	userEditDialogVisible.value = true
}

// 提交用户权限编辑
const submitUserEdit = async () => {
	if (editingPage.value && editingPage.value.id) {
		await handleAllowUserChange(editingPage.value, editingUserTypes.value)
		userEditDialogVisible.value = false
		getPageList()
	}
}

// 取消用户权限编辑
const cancelUserEdit = () => {
	userEditDialogVisible.value = false
	editingPage.value = null
	editingUserTypes.value = []
}
</script>

<template>
	<div class="page-manage" v-loading="loading">
		<el-card class="page-card">
			<!-- 卡片头部 -->
			<template #header>
				<div class="card-header">
					<h2>页面管理</h2>
					<el-button type="primary" @click="openDialog('add')">
						<el-icon><Plus /></el-icon>添加
					</el-button>
				</div>
			</template>

			<!-- 分组表格部分 -->
			<div v-for="(pages, groupName) in groupedPages" :key="groupName" class="page-group">
				<div class="group-header" @click="toggleGroup(groupName)">
					<el-icon :class="{ 'is-expanded': expandedGroups[groupName] }">
						<CaretRight />
					</el-icon>
					<h3>{{ getGroupDisplayName(groupName) }}</h3>
					<span class="group-count">({{ pages.length }})</span>
				</div>

				<div v-show="expandedGroups[groupName]" class="group-content">
					<el-table :data="pages" :show-header="true" style="width: 100%">
						<el-table-column prop="name" label="页面名称" width="120" show-overflow-tooltip />
						<el-table-column prop="path" label="页面路径" min-width="160" show-overflow-tooltip />
						<el-table-column prop="icon" label="图标" width="100" show-overflow-tooltip />
						<el-table-column
							prop="allowUser"
							label="允许用户"
							min-width="180"
							show-overflow-tooltip
						>
							<template #default="{ row }">
								{{ formatAllowUser(row.allowUser) }}
							</template>
						</el-table-column>
						<el-table-column prop="createTime" label="创建时间" width="120" show-overflow-tooltip>
							<template #default="{ row }">{{ standardDateTime(row.createTime) }}</template>
						</el-table-column>
						<el-table-column prop="isEnabled" label="状态" width="80" align="center">
							<template #default="{ row }">
								<el-switch
									:model-value="!!row.isEnabled"
									@change="
										(val: boolean) => {
											row.isEnabled = val ? 1 : 0
											handleStatusChange(row)
										}
									"
								/>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="150" fixed="right">
							<template #default="{ row }">
								<el-button-group>
									<el-button type="primary" link @click="openDialog('edit', row)">编辑</el-button>
									<el-button type="primary" link @click="openUserEditDialog(row)">权限</el-button>
									<el-button type="danger" link @click="handleDelete(row)">删除</el-button>
								</el-button-group>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>

			<!-- 弹窗表单 -->
			<el-dialog
				:title="dialogTitle"
				v-model="dialogVisible"
				align-center
				width="500px"
				:close-on-click-modal="false"
				:close-on-press-escape="false"
			>
				<div v-loading="loadingDialog" class="dialog-content">
					<el-form ref="formRef" :model="currentPage" :rules="formRule" label-width="120px">
						<el-form-item label="页面名称" prop="name">
							<el-input v-model="currentPage.name" placeholder="请输入页面名称" />
						</el-form-item>

						<el-form-item label="页面路径" prop="path">
							<el-input v-model="currentPage.path" placeholder="请输入页面路径" />
						</el-form-item>

						<el-form-item label="所在路径" prop="component">
							<el-input v-model="currentPage.component" placeholder="请输入所在路径" />
						</el-form-item>

						<el-form-item label="图标" prop="icon">
							<el-input v-model="currentPage.icon" placeholder="请输入图标" />
						</el-form-item>

						<el-form-item label="是否启用" prop="isEnabled">
							<el-switch
								:model-value="!!currentPage.isEnabled"
								@change="(val: boolean) => (currentPage.isEnabled = val ? 1 : 0)"
							/>
						</el-form-item>

						<el-form-item label="允许用户" prop="allowUser">
							<el-select
								v-model="selectedUserTypes"
								multiple
								placeholder="请选择允许的用户类型"
								@change="handleUserTypesChange"
								style="width: 100%"
							>
								<el-option
									v-for="option in userOptions"
									:key="option.value"
									:label="option.label"
									:value="option.value"
								/>
							</el-select>
							<!-- <div class="quick-actions">
								<el-button
									type="info"
									size="small"
									link
									@click="
										() => {
											selectedUserTypes = [1, 2, 3, 4, 5]
											handleUserTypesChange(selectedUserTypes)
										}
									"
								>
									全选
								</el-button>
								<el-button
									type="info"
									size="small"
									link
									@click="
										() => {
											selectedUserTypes = []
											handleUserTypesChange(selectedUserTypes)
										}
									"
								>
									清空
								</el-button>
							</div> -->
						</el-form-item>

						<el-form-item class="dialog-footer">
							<el-button type="primary" @click="pageSubmit(currentPage)">
								{{ currentPage.id ? '更新' : '添加' }}
							</el-button>
							<el-button @click="resetForm">重置</el-button>
							<el-button @click="dialogVisible = false">取消</el-button>
						</el-form-item>
					</el-form>
				</div>
			</el-dialog>

			<!-- 用户权限编辑弹窗 -->
			<el-dialog
				title="编辑页面权限"
				v-model="userEditDialogVisible"
				align-center
				width="400px"
				:close-on-click-modal="false"
			>
				<div v-if="editingPage" class="dialog-content">
					<h3>{{ editingPage.name }} - 权限设置</h3>
					<p class="dialog-subtitle">请选择允许访问的用户类型</p>
					<el-form label-width="0px">
						<el-form-item style="width: 100%">
							<el-select
								v-model="editingUserTypes"
								multiple
								placeholder="请选择允许的用户类型"
								style="width: 100%"
							>
								<el-option
									v-for="option in userOptions"
									:key="option.value"
									:label="option.label"
									:value="option.value"
								/>
							</el-select>
						</el-form-item>
						<div class="quick-actions">
							<!-- <el-button
								type="info"
								size="small"
								link
								@click="() => (editingUserTypes = [1, 2, 3, 4, 5])"
							>
								全选
							</el-button>
							<el-button type="info" size="small" link @click="() => (editingUserTypes = [])">
								清空
							</el-button> -->
						</div>
						<el-form-item class="dialog-footer" style="width: 100%">
							<el-button type="primary" @click="submitUserEdit">确认</el-button>
							<el-button @click="cancelUserEdit">取消</el-button>
						</el-form-item>
					</el-form>
				</div>
			</el-dialog>
		</el-card>
	</div>
</template>

<style scoped lang="scss">
.page-manage {
	display: flex;
	flex-wrap: wrap;
		height: 100%;

	// padding: 12px;

	:deep(.el-card) {
		margin: 10px;
		height: min-content;
		width: 100%;
		height: 95%;

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			h2 {
				margin: 0;
				font-size: 16px;
				line-height: 1.5;
				padding: 4px 0;
			}
		}
	}

	.page-card {
		min-width: 100vh;
		// max-height: 570px;
		overflow-y: auto;
	}

	.page-group {
		margin-bottom: 16px;
		border: 1px solid #ebeef5;
		border-radius: 4px;
		// overflow-y: auto;

		.group-header {
			display: flex;
			align-items: center;
			padding: 10px 15px;
			background-color: #f5f7fa;
			cursor: pointer;
			user-select: none;

			h3 {
				margin: 0 10px;
				font-size: 14px;
				font-weight: bold;
			}

			.group-count {
				color: #909399;
				font-size: 12px;
			}

			.el-icon {
				transition: transform 0.3s;
				font-size: 16px;

				&.is-expanded {
					transform: rotate(90deg);
				}
			}
		}

		.group-content {
			padding: 10px;
		}
	}
}

.dialog-content {
	// padding: 10px;

	:deep(.el-form) {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.el-form-item {
			width: 60vh;
			max-width: 450px;
		}
	}

	.dialog-subtitle {
		color: #909399;
		font-size: 14px;
		margin-bottom: 15px;
	}

	.dialog-footer {
		margin-top: 15px;
		text-align: right;
	}

	.quick-actions {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
		margin-top: 5px;
		font-size: 12px;
	}
}

// 用户选择tag的样式
:deep(.el-select .el-select__tags .el-tag) {
	background-color: #ecf5ff;
	border-color: #d9ecff;
	color: #409eff;
}
</style>
